package com.cngphone.AnFetion;

import java.util.ArrayList;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.widget.Toast;

public class FetionSendTo extends Activity {
    private String mobile;
    protected FetionService mBoundService;
    private boolean isBind = false;

    private ServiceConnection mConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName className, IBinder service) {
            mBoundService = ((FetionService.LocalBinder) service).getService();
            isBind = true;
            ArrayList<FetionFriend> buddies = mBoundService.getFriendManager().getBuddies();
            int size = buddies.size();
            FetionFriend friend = null;
            for (int i=0; i<size; i++) {
                FetionFriend f = buddies.get(i);
                if (mobile.equals(f.mobile_no)) {
                    friend = f;
                    break;
                }
            }
            if (friend == null) {
                Toast.makeText(FetionSendTo.this.getApplicationContext(), "没有此好友.", Toast.LENGTH_LONG).show();
                finish();
                return;
            }
            Intent intent = new Intent(FetionSendTo.this, SendSMSActivity.class);
            intent.putExtra("uri", friend.Uri);

            startActivityIfNeeded(intent, 0);
            finish();
        }

        @Override
        public void onServiceDisconnected(ComponentName className) {
            mBoundService = null;
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Intent intent = getIntent();
        Uri uri = intent.getData();
        if (!Intent.ACTION_SENDTO.equals(intent.getAction()) || uri == null || !"sms".equals(uri.getScheme())) {
            finish();
            return;
        }
        // dest就是联系人的手机号码了
        mobile = uri.getSchemeSpecificPart();
        mobile = MiscUtil.toMobile(mobile);
        if (mobile == null) {
            Toast.makeText(this.getApplicationContext(), "不是飞信支持的手机号码", Toast.LENGTH_LONG).show();
            finish();
            return;
        }
        if (!FetionService.isLogined()) {
            Toast.makeText(this.getApplicationContext(), "飞信未登录, 请登录后再发送.", Toast.LENGTH_LONG).show();
            finish();
            return;
        }
        // System.out.println(dest);
        this.bindService(MiscUtil.getFetionServiceIntent(this), mConnection, Context.BIND_AUTO_CREATE);
    }

    @Override
    protected void onDestroy() {
        if (isBind) {
            isBind = false;
            unbindService(mConnection);
        }
        super.onDestroy();
    }

}
